package ar.edu.utn.frsf.tpae.a2013.g03.persistencia.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ar.edu.utn.frsf.tpae.a2013.g03.persistencia.dao.SupervisorDao;
import ar.edu.utn.frsf.tpae.a2013.g03.persistencia.model.Supervisor;

@Component
public class SupervisorHibernateDao implements SupervisorDao {
	
private SessionFactory sessionFactory;
    
    // Setter utilizado por Spring.
    @Autowired(required = true)
    public void setSessionFactory(SessionFactory factory) {
      this.sessionFactory = factory;
    }
    
    private Session getCurrentSession() {
              return sessionFactory.getCurrentSession();
    }

	@Override
	public Supervisor persistir(Supervisor supervisor) {
		getCurrentSession().saveOrUpdate(supervisor);
	    /*if (supervisor.getIdUsuario() == null) {
	        getCurrentSession().save(supervisor);
	      } else {
	        getCurrentSession().update(supervisor);
	      }*/
	      return supervisor;
	}

	@Override
	public void eliminar(Supervisor supervisor) {
	    getCurrentSession().delete(supervisor);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Supervisor> listar() {
		Query query = getCurrentSession().createQuery("from " + Supervisor.class.getName());
		return query.list();
	}
	
	@Override
	public Supervisor buscarPorId(Integer id) {
		
		//TODO: implementar!
		return null;		
	}

	@Override
	public Supervisor buscarPorUsuario(String supervisor) {

		Query query = getCurrentSession().createQuery("from " + Supervisor.class.getName() + " where usr_usr = :supervisor");
		query.setString("supervisor", supervisor);
		
		return (Supervisor) query.uniqueResult();		
	}

	@Override
	public Supervisor buscarPorNombre(String nombre) {
		Query query = getCurrentSession().createQuery("from " + Supervisor.class.getName() + " where usr_nom = :nombre");
		query.setString("nombre", nombre);
		
		return (Supervisor) query.uniqueResult();		
	}

	@Override
	public Supervisor buscarPorApellido(String apellido) {
		Query query = getCurrentSession().createQuery("from " + Supervisor.class.getName() + " where usr_ape = :apellido");
		query.setString("apellido", apellido);
		
		return (Supervisor) query.uniqueResult();		
	}

}
